<?php

namespace app\stores\controller\admin\order;

use app\beautiful\helper\payment\PaymentPintuanOrderHelper;
use app\beautiful\model\finance\SettleOrderModel;
use app\beautiful\model\goods\GoodsWriteOffModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\order\OrderGoodsGroupDetailModel;
use app\beautiful\model\order\OrderGoodsModel;
use app\beautiful\model\order\OrderRecordModel;
use app\beautiful\model\order\PinTuanOrderModel;
use app\beautiful\model\partner\PartnerCommissionModel;
use app\beautiful\model\setting\LevelSettingModel;
use app\common\model\MemberMoneyDetailModel;
use app\common\model\ShopBalanceLogsModel;
use app\stores\helper\payment\PaymentGoodsOrderHelper;
use app\stores\logic\LogsLogic;
use app\stores\logic\MemberWalletLogic;
use app\beautiful\model\LevelModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\beautiful\model\order\OrderRefundModel;
use app\common\logic\DataLogic;
use app\stores\model\member\MemberLevelModel;
use app\BaseController;
use app\stores\model\order\BuyOrderModel;
use app\stores\model\order\ChargebackModel;
use app\stores\model\promotion\TeamActivityModel;
use think\facade\Db;

class Order extends BaseController{
    /**
     * 商品订单/套餐订单
     */
    public function index()

    {

        $order_id = $this->request->param('order_id/d',0);

        $order_type=$this->request->param('order_type');//普通normal拼团pin_tuan秒杀flash_sale预售pre_sale

        $order_sn=$this->request->param('order_sn');

        $goods_name=$this->request->param('goods_name');

        $status=$this->request->param('status/d',0);//10待消费14消费中15已完成

        $member_id=$this->request->param('member_id/d',0);

        $mobile=$this->request->param('mobile');

        $type=$this->request->param('type/d',0);//1菜品2产品3套餐
        $time_type = $this->request->param('time_type/d',-1);//0今日1昨日2本周3本月-1全部
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

        ];
        if($goods_name){
            $order_ids = GoodsOrderItemModel::where(['shop_id'=>$this->request->shopId])->where('goods_name','like','%'.$goods_name.'%')->column('order_id');
            $where[] = ['order_id','In',$order_ids];
        }

        if($type>0){
            $order_ids = GoodsOrderItemModel::where(['shop_id'=>$this->request->shopId,'type'=>$type])->column('order_id');
            $where[] = ['order_id','In',$order_ids];
        }
        switch ($time_type){
            case 0:
                $start_time = date("Y-m-d H:i:s",strtotime("today"));
                $end_time = date("Y-m-d H:i:s",strtotime("today")+86399);
                break;

            case 1:
                $start_time = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')-1,date('Y')));
                $end_time = date("Y-m-d H:i:s",strtotime("today")-1);
                break;

            case 2:
                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
                break;

            case 3:
                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));

                break;

        }
        if(!empty($start_time) && !empty($end_time)){
            if(!in_array($time_type,[0,1,2,3])){
                $end_time = strtotime($end_time)+86400;
            }else{
                $end_time = strtotime($end_time);
            }
            $where[] = ['add_time','between',[strtotime($start_time),$end_time]];
        }
        if($member_id == 0){

            $member_where=[

                ['shop_id','=',$this->request->shopId]

            ];

            $member_ids= MemberLevelModel::where($member_where)->column('member_id') ?? [];

            $where[]=['member_id','in',$member_ids];

        }else{

            $where[]=['member_id','=',$member_id];

        }
        if($mobile){
            $m_where[]=['mobile','like','%'.$mobile.'%'];

            $member_ids = MemberModel::where($m_where)->column('member_id') ?? [];

            $where[]=['member_id','in',$member_ids];
        }
        if($type==3 && in_array($status,[14,15])){
            $wc_order_ids = GoodsOrderModel::where(['shop_id'=>$this->request->shopId,'status'=>8])->column('order_id');
            //已完成但是未消费完
            $order_ids =$group_detail = OrderGoodsGroupDetailModel::whereIn('order_id',$wc_order_ids)->where('remain_num','>',0)->where(['is_delete'=>0])->column('order_id');
            if($status==14){
                $where[]=['order_id','in',$order_ids];
            }
            if($status==15){
                $where[]=['status','=',8];
                $where[]=['order_id','not in',$order_ids];
            }
        }

        if(!empty($status) && !in_array($status,[14,15])) $where[]=['status','=',$status];

        if(!empty($order_id)) $where[]=['order_id','=',$order_id];

        if(!empty($order_type)) $where[]=['order_type','=',$order_type];

        if(!empty($order_sn)) $where[]=['order_sn','like','%'.$order_sn.'%'];
        $model=new GoodsOrderModel();

        $order_model=$model->with(['skus','member','partnerCommission']);

        $order=['add_time'=>'desc'];

        $field="order_id,member_id,order_sn,order_type,logistics_type,total_price,need_pay,add_time,pay_time,status,pay_type,order_send_time";

        $append=['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean'];

        $return = DataLogic::getDataList($order_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        //处理数据
        $lists = $return['list'];

        if(empty(!$lists)){

            $key_start = $this->request->limit * ($this->request->page - 1);
            $key_end = $return['total'];

            foreach ($lists as $k => $list){
                $lists[$k]['member_nick_name'] = $list['member']?$list['member']['nick_name']:null;
                $lists[$k]['member_face'] = $list['member']?$list['member']['face']:null;
                $lists[$k]['member_mobile'] = $list['member']?$list['member']['mobile']:null;
                $level_id = getMemberLevel($list['member_id'],$this->request->shopId);
                $level = LevelModel::find($level_id);
                $lists[$k]['level_name'] = $level?$level['name']:null;
                unset($lists[$k]['member']);

                $lists[$k]['show_order_id']= $key_end - ($key_start + $k);

                if($list['order_send_time']) $lists[$k]['order_send_time'] = json_decode($list['order_send_time'],true);
                $commission = 0;
                foreach ($list['partnerCommission'] as $key=>$value){

                    $commission += $value['commission'];
                }
                unset($lists[$k]['partnerCommission']);
                //股东提成
                $lists[$k]['percentage'] = sprintf("%.2f",$commission);
                //商家实收
                $lists[$k]['boss_real_receive'] = sprintf("%.2f",$list['need_pay'] - $list['freight'] - $commission - $list['coupon_money']);

                //数量和优惠
                $return_youhui = $this->youhui($list);
                $lists[$k]['goods_name'] = $return_youhui['goods_name'];
                $lists[$k]['total_num'] = $return_youhui['total_num'];
                $lists[$k]['youhui_name'] = $return_youhui['youhui_name'];
                $lists[$k]['youhui'] = $return_youhui['youhui'];
                $lists[$k]['activity'] = $return_youhui['activity'];
                $lists[$k]['is_bf_refund'] = ($list['refund_money']>0 && $list['status']!=12)?1:0;
                $lists[$k]['need_pay'] = $list['status']<2?0:$lists[$k]['need_pay'] - $list['refund_money'];
                $lists[$k]['youhui_price'] = $return_youhui['youhui_price'] + $list['integral_balance'] + $list['coupon_money'];

            }
        }


        $return['list']=$lists;
        //订单总金额
        $total_price = $model->where($where)->sum('total_price');
        //订单总实付
        $total_need_pay = $model->where($where)->where('status','>',1)->sum('need_pay');
        $refund_money = $model->where($where)->where('status','>',1)->sum('refund_money');
        //订单总优惠
        $total_integral_balance = $model->where($where)->sum('integral_balance');
        $total_coupon_money = $model->where($where)->sum('coupon_money');
        //退款统计
        $total_refund_money = $model->where($where)->where(['status'=>12])->sum('need_pay');
        //全额退款数
        $all_refund_count = $model->where($where)->where(['status'=>12])->count();

        $return['total_youhui'] = sprintf("%.2f",$total_integral_balance + $total_coupon_money);
        $return['total_price'] = sprintf("%.2f",$total_price);
        $return['total_pay_money'] = sprintf("%.2f",$total_need_pay - $refund_money);
        $return['total_refund_money'] = sprintf("%.2f",$total_refund_money);
        $return['all_refund_count'] = $all_refund_count;
        return $this->success($return);



    }
    public function indexOld()

    {

        $order_id = $this->request->param('order_id/d',0);

        $order_type=$this->request->param('order_type');//普通normal拼团pin_tuan秒杀flash_sale预售pre_sale

        $order_sn=$this->request->param('order_sn');

        $goods_name=$this->request->param('goods_name');

        $status=$this->request->param('status/d',0);

        $member_id=$this->request->param('member_id/d',0);

        $mobile=$this->request->param('mobile');

        $type=$this->request->param('type/d',0);//1菜品2产品3套餐
        $time_type = $this->request->param('time_type/d',-1);//0今日1昨日2本周3本月-1全部
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

        ];
        if($goods_name){
            $order_ids = GoodsOrderItemModel::where(['shop_id'=>$this->request->shopId])->where('goods_name','like','%'.$goods_name.'%')->column('order_id');
            $where[] = ['order_id','In',$order_ids];
        }

        if($type>0){
            $order_ids = GoodsOrderItemModel::where(['shop_id'=>$this->request->shopId,'type'=>$type])->column('order_id');
            $where[] = ['order_id','In',$order_ids];
        }
        switch ($time_type){
            case 0:
                $start_time = date("Y-m-d H:i:s",strtotime("today"));
                $end_time = date("Y-m-d H:i:s",strtotime("today")+86399);
                break;

            case 1:
                $start_time = date('Y-m-d H:i:s',mktime(0,0,0,date('m'),date('d')-1,date('Y')));
                $end_time = date("Y-m-d H:i:s",strtotime("today")-1);
                break;

            case 2:
                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
                break;

            case 3:
                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));

                break;

        }
        if(!empty($start_time) && !empty($end_time)){
            if(!in_array($time_type,[0,1,2,3])){
                $end_time = strtotime($end_time)+86400;
            }else{
                $end_time = strtotime($end_time);
            }
            $where[] = ['add_time','between',[strtotime($start_time),$end_time]];
        }
        if($member_id == 0){

            $member_where=[

                ['shop_id','=',$this->request->shopId]

            ];

            $member_ids= MemberLevelModel::where($member_where)->column('member_id') ?? [];

            $where[]=['member_id','in',$member_ids];

        }else{

            $where[]=['member_id','=',$member_id];

        }
        if($mobile){
            $m_where[]=['mobile','like','%'.$mobile.'%'];

            $member_ids = MemberModel::where($m_where)->column('member_id') ?? [];

            $where[]=['member_id','in',$member_ids];
        }

        if(!empty($status)) $where[]=['status','=',$status];

        if(!empty($order_id)) $where[]=['order_id','=',$order_id];

        if(!empty($order_type)) $where[]=['order_type','=',$order_type];

        if(!empty($order_sn)) $where[]=['order_sn','like','%'.$order_sn.'%'];
        $model=new GoodsOrderModel();

        $order_model=$model->with(['skus','member','partnerCommission']);

        $order=['add_time'=>'desc'];

        $field="order_id,member_id,order_sn,order_type,logistics_type,total_price,need_pay,add_time,pay_time,status,pay_type,order_send_time";

        $append=['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean'];

        $return = DataLogic::getDataList($order_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        //处理数据
        $lists = $return['list'];

        if(empty(!$lists)){

            $key_start = $this->request->limit * ($this->request->page - 1);
            $key_end = $return['total'];

            foreach ($lists as $k => $list){
                $lists[$k]['member_nick_name'] = $list['member']?$list['member']['nick_name']:null;
                $lists[$k]['member_face'] = $list['member']?$list['member']['face']:null;
                $lists[$k]['member_mobile'] = $list['member']?$list['member']['mobile']:null;
                $level_id = getMemberLevel($list['member_id'],$this->request->shopId);
                $level = LevelModel::find($level_id);
                $lists[$k]['level_name'] = $level?$level['name']:null;
                unset($lists[$k]['member']);

                $lists[$k]['show_order_id']= $key_end - ($key_start + $k);

                if($list['order_send_time']) $lists[$k]['order_send_time'] = json_decode($list['order_send_time'],true);
                $commission = 0;
                foreach ($list['partnerCommission'] as $key=>$value){

                    $commission += $value['commission'];
                }
                unset($lists[$k]['partnerCommission']);
                //股东提成
                $lists[$k]['percentage'] = sprintf("%.2f",$commission);
                //商家实收
                $lists[$k]['boss_real_receive'] = sprintf("%.2f",$list['need_pay'] - $list['freight'] - $commission - $list['coupon_money']);

                //数量和优惠
                $return_youhui = $this->youhui($list);
                $lists[$k]['goods_name'] = $return_youhui['goods_name'];
                $lists[$k]['total_num'] = $return_youhui['total_num'];
                $lists[$k]['youhui_name'] = $return_youhui['youhui_name'];
                $lists[$k]['youhui'] = $return_youhui['youhui'];
                $lists[$k]['activity'] = $return_youhui['activity'];
                $lists[$k]['is_bf_refund'] = ($list['refund_money']>0 && $list['status']!=12)?1:0;
                $lists[$k]['need_pay'] = $list['status']<2?0:$lists[$k]['need_pay'] - $list['refund_money'];
                $lists[$k]['youhui_price'] = $return_youhui['youhui_price'];

            }
        }


        $return['list']=$lists;
        //订单总金额
        $total_price = $model->where($where)->sum('total_price');
        //订单总实付
        $total_need_pay = $model->where($where)->where('status','>',1)->sum('need_pay');
        $refund_money = $model->where($where)->where('status','>',1)->sum('refund_money');
        //订单总优惠
        $total_integral_balance = $model->where($where)->sum('integral_balance');
        $total_coupon_money = $model->where($where)->sum('coupon_money');
        //退款统计
        $total_refund_money = $model->where($where)->where(['status'=>12])->sum('need_pay');
        //全额退款数
        $all_refund_count = $model->where($where)->where(['status'=>12])->count();

        $return['total_youhui'] = sprintf("%.2f",$total_integral_balance + $total_coupon_money);
        $return['total_price'] = sprintf("%.2f",$total_price);
        $return['total_pay_money'] = sprintf("%.2f",$total_need_pay - $refund_money);
        $return['total_refund_money'] = sprintf("%.2f",$total_refund_money);
        $return['all_refund_count'] = $all_refund_count;
        return $this->success($return);



    }
    private function youhui($datas){
        $youhui_name = $goods_name = '';
        $youhui = [];
        $activity = '无';
        //优惠券折扣
        if($datas['member_coupon_id']>0){
            $coupon = MemberCouponModel::with(['couponInfo'])->where(['member_coupon_id'=>$datas['member_coupon_id']])->find();
            if($coupon){
                $coupon = $coupon->toArray();
                $youhui[] = [
                    'discount_name'=>$coupon['couponInfo']['name'],
                    'discount_price'=>$datas['coupon_money']
                ];
                $youhui_name.='/券抵扣';
            }
        }
        //优惠
        if($datas['order_type']=='pin_tuan'){
            $youhui[] = [
                'discount_name'=>'拼团价',
                'discount_price'=>$datas['coupon_money']
            ];
            $youhui_name.='/拼团';
            $activity = '拼团';
        }
        if($datas['order_type']=='flash_sale'){
            $youhui[] = [
                'discount_name'=>'秒杀价',
                'discount_price'=>$datas['coupon_money']
            ];
            $youhui_name.='/秒杀';
            $activity = '秒杀';
        }
        if($datas['team_activity_id']){
            $activity_info = TeamActivityModel::ainfo(['team_activity_id'=>$datas['team_activity_id']],'a.type');
            if($activity_info){
                $activity = $activity_info['type']==1?'地推':'推广';
            }

        }

        $data = $datas['skus'];
        //数量
        $total_num = $youhui_price = 0;
        foreach ($data as $k=>$v){
            if($k==0){
                $goods_name.=$v['goods_name'];
            }
            if($k==1){
                $goods_name.='...';
            }
            $total_num += $v['goods_num'];
            //会员折扣
            if($v['vip_discount_type']>0){
                if($v['vip_discount_type'] == 1){
                    $discount_name = $v['discount_detail'].'折';
                    if($youhui_name=='') $youhui_name='/会员折扣';
                }else if($v['vip_discount_type'] == 2){
                    $discount_name = '指定价格';
                }else if($v['vip_discount_type'] == 3){
                    $discount_name = '减价';
                }
                if(empty($youhui)){
                    $youhui[] = [
                        'discount_name'=>$discount_name,
                        'discount_price'=>sprintf("%.2f",$v['goods_original_price']-$v['goods_price'])
                    ];
                }
                $toal_chargeback_num = ChargebackModel::where(['shop_id'=>$this->request->shopId,'order_item_id'=>$v['order_item_id'],'is_delete'=>0])->sum('num');
                $youhui_price += sprintf("%.2f",($v['goods_original_price']-$v['goods_price']) * ($v['goods_num'] - $toal_chargeback_num));
            }

        }

        $return = [
            'goods_name'=>$goods_name,
            'total_num'=>$total_num,
            'youhui_name'=>$youhui_name!=''?substr($youhui_name,1):'',
            'youhui'=>$youhui,
            'activity'=>$activity,
            'youhui_price'=>$youhui_price,
        ];

        return $return;
    }
    /**
     * 收款/买单订单
     */
    public function buyOrderList(){
        $member_num=$this->request->param('member_num');
        $mobile=$this->request->param('mobile');
        $time_type = $this->request->param('time_type/d',-1);//0今日1昨日2本周3本月
        $start_time = $this->request->param('start_time');
        $end_time = $this->request->param('end_time');

        $where=[
            ['shop_id','=',$this->request->shopId],
        ];
        switch ($time_type){
            case 0:
                $start_time = date("Y-m-d H:i:s",strtotime("today"));
                $end_time = date("Y-m-d H:i:s",strtotime("today")+86399);
                break;

            case 1:
                $start_time = date('Y-m-d',mktime(0,0,0,date('m'),date('d')-1,date('Y')));
                $end_time = date("Y-m-d H:i:s",strtotime("today")-1);
                break;

            case 2:
                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")));
                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")));
                break;

            case 3:
                $start_time = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $end_time = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));

                break;

        }
      
        if(!empty($start_time) && !empty($end_time)){
            if(!in_array($time_type,[0,1,2,3])){
                $end_time = strtotime($end_time)+86400;
            }else{
                $end_time = strtotime($end_time);
            }
            $where[] = ['add_time','between',[strtotime($start_time),$end_time]];
        }

        $member_where = [];

        if(!empty($member_num)) $member_where[]=['member_num','like','%'.$member_num.'%'];
        if(!empty($mobile)) $member_where[]=['mobile','like','%'.$mobile.'%'];

        if($member_where){
            $member_ids= MemberModel::where($member_where)->column('member_id') ?? [];
            $where[]=['member_id','in',$member_ids];
        }

        $model=new BuyOrderModel();
        $order_model=$model->with(['member']);

        $order=['add_time'=>'desc'];
        $field="*";
        $append = ['add_time_format','pay_time_format','pay_type_mean','price','discount_money'];

        $b_where = $where;
        $b_where[] = ['status','>',0];
        $return = DataLogic::getDataList($order_model,$b_where,$order,$field,$this->request->limit,$this->request->page,$append);

        $list = $return['list'];

        foreach ($list as $k=>$v){
            $list[$k]['member_nick_name'] = $v['member']?$v['member']['nick_name']:null;
            $list[$k]['member_face'] = $v['member']?$v['member']['face']:null;
            $list[$k]['member_mobile'] = $v['member']?$v['member']['mobile']:null;
            $list[$k]['member_num'] = $v['member']?$v['member']['member_num']:null;
            $level_id = getMemberLevel($v['member_id'],$this->request->shopId);
            $level = LevelModel::find($level_id);
            $list[$k]['level_name'] = $level?$level['name']:null;
            unset($list[$k]['member']);

            $youhui = $this->buyYouhui($v);
            $list[$k]['youhui_name'] = $youhui['youhui_name'];
            $list[$k]['youhui'] = $youhui['youhui'];
            //是否已全退款
            $list[$k]['is_bf_refund'] = ($v['refund_money']>0 && $v['status']!=3)?1:0;
            //实付-退款
            $list[$k]['pay_money'] = $list[$k]['pay_money'] - $list[$k]['refund_money'];
        }

        $return['list'] = $list;
        //订单总金额
        $total_balance = $model->where($b_where)->sum('balance');
        //订单总实付
        $total_pay_money = $model->where($b_where)->sum('pay_money');
        //订单总优惠
        $total_vip_balance = $model->where($b_where)->sum('vip_balance');
        $total_coupon_money = $model->where($b_where)->sum('coupon_money');
        //退款统计
        $total_refund_money = $model->where($b_where)->sum('refund_money');
        //部分
        $bf_refund_count = $model->where($b_where)->where('refund_money>0 and status!=3')->count();
        //全部
        $all_refund_count = $model->where($where)->where(['status'=>3])->count();

        $return['total_youhui'] = sprintf("%.2f",$total_vip_balance + $total_coupon_money);
        $return['total_balance'] = sprintf("%.2f",$total_balance);
        $return['total_pay_money'] = sprintf("%.2f",$total_pay_money);
        $return['total_refund_money'] = sprintf("%.2f",$total_refund_money);
        $return['bf_refund_count'] = $bf_refund_count;
        $return['all_refund_count'] = $all_refund_count;
        return $this->success($return);
    }

    private function buyYouhui($datas){
        $youhui_name = '';
        $youhui = [];
        //优惠券折扣
        if($datas['member_coupon_id']>0){
            $coupon = MemberCouponModel::with(['couponInfo'])->where(['member_coupon_id'=>$datas['member_coupon_id']])->find();
            if($coupon){
                $coupon = $coupon->toArray();
                $youhui[] = [
                    'discount_name'=>$coupon['couponInfo']['name'],
                    'discount_price'=>$datas['coupon_money']
                ];
                $youhui_name.='/券抵扣';
            }
        }
        //会员折扣
        if($datas['discount_detail']>0){
            $youhui_name.='/会员折扣';
            $youhui[] = [
                'discount_name'=>$datas['discount_detail'].'折',
                'discount_price'=>$datas['balance']/$datas['discount_detail']-$datas['balance']
            ];
        }
        $return = [
            'youhui_name'=>$youhui_name!=''?substr($youhui_name,1):'',
            'youhui'=>$youhui,
        ];

        return $return;
    }

    /**
     * 退款订单
     */
    public function refundOrderList(){
        $order_type=$this->request->param('order_type');//普通normal拼团pin_tuan秒杀flash_sale预售pre_sale套餐set_meal
        $status = $this->request->param('status');//0退款中1退款成功-1退款失败
        $order_sn = $this->request->param('order_sn');
        $mobile = $this->request->param('mobile');
        $goods_name = $this->request->param('goods_name');
        $member_id = $this->request->param('member_id');

        $limit=$this->request->limit;
        $page=$this->request->page;

        $where['shop_id']=$this->request->shopId;
        if(!empty($order_type)) $where['order_type']=$order_type;
        if($status!='') $where['status']=$status;
        if(!empty($order_sn)) $where['order_sn']=$order_sn;
        if(!empty($mobile)) $where['mobile']=$mobile;
        if(!empty($goods_name)) $where['goods_name']=$goods_name;
        if(!empty($member_id)) $where['member_id']=$member_id;

        $return = OrderRefundModel::list($where,['add_time'=>'desc'],$page,$limit);
        return $this->success($return);
    }
    /**
     *退款列表/退款详情
     */
    public function refundOrderDetail(){
        $order_refund_id = $this->request->param('order_refund_id');
        if(null === $refund = OrderRefundModel::where(['order_refund_id'=>$order_refund_id])->find()){
            return $this->error('退款申请不存在');
        }

        
        return $this->success('操作成功');
    }
    /**
     * 同意退款
    */
    public function refund(){
        $order_refund_id = $this->request->param('order_refund_id');
        if(null === $refund = OrderRefundModel::where(['order_refund_id'=>$order_refund_id])->find()){
            return $this->error('退款申请不存在');
        }
        if($refund->status!==0) return $this->error('该退款已处理');

        $order = \app\stores\model\order\GoodsOrderModel::where(['order_id'=>$refund->order_id])->find();
        $order = $order->toArray();
        if($order['status']!=11) return $this->error('该退款已处理');
        if($order['is_settle']==1) return $this->error('该订单已结算不能退款');
        Db::startTrans();
        try{
            //退还优惠券
            if(!empty($order['member_coupon_id'])){

                if(null === $myCoupon = MemberCouponModel::find($order['member_coupon_id'])){

                    return $this->error('优惠券不存在');

                }

                if($myCoupon->status == 0){

                    return $this->error('优惠券还未使用');

                }

                $myCoupon->status = 0;

                $myCoupon->save();

                LogsLogic::coupon($this->request->shopId, $order['member_id'], 1, 23, $order['member_coupon_id'], '', 0);

            }
            //退还积分
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $order['member_id']);

            if(!empty($order['use_integral'])){ //使用积分

                $res = $MemberWalletLogic->addIntegal($order['use_integral'], 23);

                if($res == false){

                    return $this->error($MemberWalletLogic->getError());

                }

            }
            if(!empty($order['mix_pay_type'])){
                $return = mix_refund_money($order,$refund);
                if(!$return['code']){
                    return  $this->error($return['error']);
                }
            }else{
                if($order['pay_type'] == 'weixin'){
                    //支付原路退还
                    $PaymentGoodsOrderHelper = new PaymentGoodsOrderHelper($this->request->shopId);
                    $re= $PaymentGoodsOrderHelper->refundInTheSameWay($order['pay_info']);
                    if($re['result_code']=='FAIL'){
                        return $this->error($re['err_code_des']);
                    }

                }

                if($order['pay_type'] == 'money'){
                    $res = $MemberWalletLogic->rebackBalance($refund->refund_price, 0 , 23); //商城购物使用
                    if($res == false){
                        return $this->error($MemberWalletLogic->getError());
                    }

                }

                if($order['pay_type'] == 'platform_money'){
                    $member = MemberModel::where(['member_id'=>$order['member_id']])->find();

                    $money = $member->money;

                    $member->money = $member->money+$refund->refund_price;
                    $member->save();

                    LogsLogic::money($this->request->shopId, $order['member_id'], 23, 1, $money,$refund->refund_price, $member->money+$refund->refund_price,0,$order['order_id'],$order['pin_tuan_order_id']);
                }
            }

            //修改状态
            $refund->status = 1;
            $refund->update_time = date('Y-m-d H:i:s');
            $refund->save();

            $update_data['refund_money'] = $order['refund_money'] + $refund['refund_price'];
            $update_data['status'] = 12;
            $update_data['edit_time'] = date('Y-m-d H:i:s');
            \app\stores\model\order\GoodsOrderModel::where(['order_id'=>$refund->order_id])->save($update_data);

            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = 6;
            $r_data['order_refund_id'] = $order_refund_id;
            $r_data['operate_id'] = $this->request->accountId;
            add_record(0,$order['order_id'],$r_data);

            //删除分佣数据
            ShopBalanceLogsModel::where(['order_id'=>$order['order_id']])->delete();
            //删除股东推广分成
            MemberMoneyDetailModel::where(['g_order_id'=>$order['order_id'],'type'=>4])->delete();
            //删除股东佣金表
            $type = $order['order_type']=='pin_tuan'?'拼团订单':'普通订单';
            PartnerCommissionModel::where(['order_id'=>$order['order_id'],'type'=>$type])->delete();

            Db::commit();

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('操作成功');
    }

    /**
     * 拒绝退款
     */
    public function refuseRefund(){
        $order_refund_id = $this->request->param('order_refund_id');
        $reason = $this->request->param('reason');
        if(null === $refund = OrderRefundModel::where(['order_refund_id'=>$order_refund_id])->find()){
            return $this->error('退款申请不存在');
        }
        Db::startTrans();

        try{
            $refund->reason = $reason;
            $refund->status = -1;
            $refund->save();
            $order = \app\stores\model\order\GoodsOrderModel::where(['order_id'=>$refund->order_id])->find();
            $order = $order->toArray();
//            $item = GoodsOrderItemModel::where(['order_id'=>$refund->order_id])->find();
//            $item = $item->toArray();

            $status=10;
            if($order['logistics_type'] == 1){
                $status=2;
            }
            if($order['logistics_type'] == 2){
                $status=4;
            }
            if($order['logistics_type'] == 3){
                $status=9;
            }
            $update_data['status'] = $status;
            $update_data['edit_time'] = date('Y-m-d H:i:s');
            \app\stores\model\order\GoodsOrderModel::where(['order_id'=>$refund->order_id])->save($update_data);

            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = 7;
            $r_data['order_refund_id'] = $order_refund_id;
            $r_data['operate_id'] = $this->request->accountId;
            add_record(0,$order['order_id'],$r_data);

            Db::commit();

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('操作成功');
    }
    /**
     *买单退款（可部分）
     */
    public function buyRefund(){
        $refund_type = $this->request->param('refund_type',1);//1全额退款2部分退款
        $refund_money = $this->request->param('refund_money',0);
        $reason = $this->request->param('reason');
        $buy_order_id = $this->request->param('buy_order_id');

        if(null === $order = BuyOrderModel::where(['buy_order_id'=>$buy_order_id,'is_paid'=>1,'shop_id'=>$this->request->shopId])->find()){
            return $this->error('买单订单不存在');
        }

        if($order['is_paid'] < 1 || $order['status'] < 1) return $this->error('该订单未支付');
        if($order['is_settle'] ==1) return $this->error('该订单已结算不能退款');
        if($refund_type==2 && ($refund_money <= 0)) return $this->error('退款金额必须大于0');
        if($refund_money > ($order['pay_money'] - $order['refund_money'])) return $this->error('退款金额大于可退款金额');
        if($refund_type == 2 && $order['pay_money'] == $refund_money) return $this->error('部分退款金额已是全额金额，请选全额退款');
        if($order['pay_money'] == $order['refund_money']) return $this->error('已全部退完');
        if($refund_type == 1 && $order['refund_money']>0) return $this->error('已部分退款');

        $refund_money = $refund_type==1?$order['pay_money']:$refund_money;

        Db::startTrans();
        try{

            //退还优惠券
            if(!empty($order['member_coupon_id'])){

                if(null === $myCoupon = MemberCouponModel::find($order['member_coupon_id'])){

                    return $this->error('优惠券不存在');

                }

                if($myCoupon->status == 0){

                    return $this->error('优惠券还未使用');

                }

                $myCoupon->status = 0;

                $myCoupon->save();

                LogsLogic::coupon($this->request->shopId, $order['member_id'], 1, 23, $order['member_coupon_id'], '', 0);

            }

            //退还积分
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $order['member_id']);

            if(!empty($order['use_integral'])){ //使用积分

                $res = $MemberWalletLogic->addIntegal($order['use_integral'], 23);

                if($res == false){

                    return $this->error($MemberWalletLogic->getError());

                }

            }
            if(!empty($order['mix_pay_type'])){
                $refund_money = $refund_type==1?$order->pay_money:$refund_money;
                $return = buy_mix_refund_money($order,$refund_money);
                if(!$return['code']){
                    return  $this->error($return['error']);
                }
                $refund_money = $return['refund_platform_money'] + $return['refund_money'] + $return['refund_weixin'];
                $refund_platform_money = $return['refund_platform_money'];
                $refund_price = $return['refund_money'];
                $refund_weixin = $return['refund_weixin'];
            }else{
                $refund_platform_money = $refund_price = $refund_weixin = 0;
                if($order['pay_type'] == 'weixin'){
                    $pay_info = $order['pay_info'];
                    $pay_info['refund_total_fee'] = $refund_money * 100;
                    $pay_info['out_refund_no'] = $refund_order_sn = createOrderSn($buy_order_id,5);
                    //支付原路退还
                    $PaymentGoodsOrderHelper = new PaymentGoodsOrderHelper($this->request->shopId);
                    $re= $PaymentGoodsOrderHelper->refundInTheSameWayBf($pay_info);

                    if($re['result_code']=='FAIL'){
                        return $this->error($re['err_code_des']);
                    }
                    $refund_weixin = $refund_money;
                }

                if($order['pay_type'] == 'money'){
                    $res = $MemberWalletLogic->rebackBalance($refund_money, 0 , 24); //商城购物使用
                    if($res == false){
                        return $this->error($MemberWalletLogic->getError());
                    }
                    $refund_price = $refund_money;
                }

                if($order['pay_type'] == 'platform_money'){
                    $member = MemberModel::where(['member_id'=>$order['member_id']])->find();

                    $money = $member->money;

                    $member->money = $member->money+$refund_money;
                    $member->save();

                    LogsLogic::money($this->request->shopId, $order['member_id'], 24, 1, $money,$refund_money, $member->money+$refund_money,$order['buy_order_id'],0,0);
                    $refund_platform_money = $refund_money;
                }
            }


            $order_refund = new OrderRefundModel();

            if(isset($refund_order_sn)) $order_refund->refund_order_sn = $refund_order_sn;

            $order_refund_data['shop_id'] = $this->request->shopId;
            $order_refund_data['buy_order_id'] = $buy_order_id;
            $order_refund_data['member_id'] = $order['member_id'];
            $order_refund_data['refund_price'] = $refund_money;
            $order_refund_data['remain_money'] = $order['pay_money'] -$order['refund_money'] - $refund_money;
            $order_refund_data['pay_money'] = $order['pay_money'];
            $order_refund_data['status'] = 1;
            $order_refund_data['reason'] = $reason;
            $order_refund_data['refund_type'] = $refund_type;
            $order_refund_data['update_time'] = date('Y-m-d H:i:s');
            $order_refund_data['operate_id'] = $this->request->accountId;
            $order_refund_data['refund_platform_money'] = $refund_platform_money;
            $order_refund_data['refund_money'] = $refund_price;
            $order_refund_data['refund_weixin'] = $refund_weixin;
            $order_refund_id = OrderRefundModel::insertGetId($order_refund_data);

            //修改订单状态
            if(($order['refund_money'] + $refund_money) == $order->pay_money)   $order->status = 3;
            $order->reason = $reason;
            $order->edit_time = date('Y-m-d H:i:s');
            $order->refund_money = $order['refund_money'] + $refund_money;
            $order->save();

            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = $refund_type;
            $r_data['order_refund_id'] = $order_refund_id;
            $r_data['operate_id'] = $this->request->accountId;
            add_record($buy_order_id,0,$r_data);

            //是否全部退完
            if($order->refund_money == $order['pay_money']){
                //删除分佣数据
                ShopBalanceLogsModel::where(['b_order_id'=>$buy_order_id])->delete();
                //删除股东推广分成
                MemberMoneyDetailModel::where(['b_order_id'=>$buy_order_id,'type'=>4])->delete();
                //删除股东佣金表
                PartnerCommissionModel::where(['order_id'=>$buy_order_id,'type'=>'买单订单'])->delete();
            }

            Db::commit();

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('操作成功');
    }
    /*订单详情*/
    public function detail()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#');

        $order_model = new GoodsOrderModel();

        $order_model = $order_model->with(['partnerCommission','partner','item']);


        if(null === $order = $order_model->where(['order_id'=>$order_id])->json(['order_send_time'],true)->find()) return $this->error('订单不存在#');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#');

        if($order->is_delete != 0) return $this->error('订单不存在#');



        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');



        $items=GoodsOrderItemModel::with(['chargeback'])

            ->where([

            ['shop_id','=',$this->request->shopId],

            ['order_id','=',$order_id]

        ])->select()->toArray();

        if(empty($items)) return $this->error('订单不存在#7');
        $youhui_price = 0;
        foreach ($items as $k=>$v){
            $toal_chargeback_num = ChargebackModel::where(['shop_id'=>$this->request->shopId,'order_item_id'=>$v['order_item_id'],'is_delete'=>0])->sum('num');
            $items[$k]['turnover'] = $v['goods_num'] - $toal_chargeback_num;
            $items[$k]['reduce_money'] = sprintf("%.2f",($v['goods_original_price'] - $v['goods_price']) * $items[$k]['turnover']);
            $youhui_price += $items[$k]['reduce_money'];
            //单位
            $goods = GoodsModel::with(['unit'])->where(['goods_id'=>$v['goods_id']])->find();
            if($goods && isset($goods['unit']) && $goods['unit']){
                $unit = $goods['unit']['group_detail_name'];
            }
            $items[$k]['unit'] = isset($unit)?$unit:'无';
        }

        $order->append(['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean']);

        $commission = 0;

        foreach ($order->partnerCommission as $key=>$value){

            $commission += $value['commission'];
        }

        //股东提成
        $percentage = $commission;
        //商家实收
        $boss_real_receive = $order->status>1?$order->need_pay - $order->freight - $commission - $order->coupon_money - $order->refund_money:0;

        $partner_role_name = '未知';

        if($order['partner']){
            if($order['partner']['role_id']==1){
                $partner_role_name = '股东';
            }
            if($order['partner']['role_id']==2){
                $partner_role_name = '员工';
            }
            if($order['partner']['role_id']==3){
                $partner_role_name = '会员';
            }
            if($order['partner']['role_id']==4){
                $partner_role_name = '自定义';
            }
            if($order['partner']['role_id']==5){
                $partner_role_name = '投资合伙人';
            }
            if($order['partner']['role_id']==6){
                $partner_role_name = '储值合伙人';
            }
        }
        $pay_time_format = $order->pay_time_format;
        //拼团订单
        if($order['order_type']=='pin_tuan'){

            $pin_tuan_order = PinTuanOrderModel::find($order['pin_tuan_order_id']);
            $pay_time_format = date('Y-m-d H:i:s',$pin_tuan_order->pay_time);

        }
        //退款信息
        $refund_order = OrderRefundModel::where(['shop_id'=>$this->request->shopId,'order_id'=>$order_id,'is_delete'=>0])->select();

        //混合支付
        $mix_pay_money=[];

        $pay_type = $order->mix_pay_type??$order->pay_type;

        if($order->status>1 && $pay_type){

            $mix_pay_type = explode(',',$pay_type);

            for($i=0;$i<count($mix_pay_type);$i++){
                if($mix_pay_type[$i]=='money'){
                    $mix_pay_money[] = [
                        'pay_type'=>'储值卡支付',
                        'pay_money'=>$order->money,
                    ];
                }
                if($mix_pay_type[$i]=='platform_money'){
                    $mix_pay_money[] = [
                        'pay_type'=>'钱包支付',
                        'pay_money'=>$order->platform_money,
                    ];
                }
                if($mix_pay_type[$i]=='weixin'){
                    $mix_pay_money[] = [
                        'pay_type'=>'微信支付',
                        'pay_money'=>$order->weixin,
                    ];
                }

            }
        }
        //等级
        $select_setting = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1])->find();

        if(empty($select_setting)) $select_setting->type = 0;

        $member_level_model = new MemberLevelModel();

        $level_model = new LevelModel();

        $member_level = $member_level_model->getById(['shop_id'=>$this->request->shopId,'member_id'=>$order->member_id,'is_delete'=>0]);

        if($member_level) $level_info = $level_model->getById(['shop_id'=>$this->request->shopId,'level_id'=>$member_level['level_id'],'is_delete'=>0,'type'=>$select_setting->type]);

        //操作日志
        $record_return = OrderRecordModel::list(['shop_id'=>$this->request->shopId,'order_id'=>$order_id],['r.add_time'=>'asc'],0,0,'r.order_id,r.buy_order_id,r.add_time,r.status,r.operate_id,a.username as operate_name,a.mobile');

        //套餐的核销记录
        if($order['order_type'] == 'set_meal'){
            //套餐分组详情有效期
            $valid_time = $this->valid_write_off($order,$order->item);
            //剩余
            $r_where['shop_id'] = $this->request->shopId;
            $r_where['order_id'] = $order_id;
            $r_where['remain_num'] = 0;
            //排除已核销完的
            $over_ids = GoodsWriteOffModel::where($r_where)->column('order_goods_group_detail_id');
            $r_where['over_ids'] = $over_ids;
            $residue = GoodsWriteOffModel::residueList($r_where,['o.add_time'=>'desc'],0,0,'o.*,d.goods_name,d.unit');
            $write_off = GoodsWriteOffModel::List(['shop_id'=>$this->request->shopId,'order_id'=>$order_id],['o.add_time'=>'asc'],0,0,'o.*,d.goods_name,d.unit,a.username as operate_name,a.mobile');
            //已完成但是未消费完
            if($order['status'] == 8){
                $remain_group_detail = OrderGoodsGroupDetailModel::where('remain_num','>',0)->where(['order_id'=>$order_id,'is_delete'=>0])->find();
                $status = $remain_group_detail?14:15;
            }

        }

        $detail=[

            'order_id'=>$order->order_id,

            'order_type'=>$order->order_type,

            'order_sn'=>$order->order_sn,

            'logistics_type'=>$order->logistics_type,

            'add_time_format'=>$order->add_time_format,

            'order_type_means'=>$order->order_type_means,

            'status'=>isset($status)?$status:$order->status,

            'status_means'=>$order->status_means,

            'need_pay'=>$order->need_pay,

            'pay_type'=>$order->pay_type,

            'pay_type_mean'=>$order->pay_type_mean,

            'pay_time_format'=>$pay_time_format,

            'receiving_name'=>$order->receiving_name,

            'receiving_mobile'=>$order->receiving_mobile,

            'receiving_address_province'=>$order->receiving_address_province,

            'receiving_address_city'=>$order->receiving_address_city,

            'receiving_address_county'=>$order->receiving_address_county,

            'receiving_address_info'=>$order->receiving_address_info,

            'total_price'=>$order->total_price,

            'youhui_balance'=>$order->youhui_balance,

            'freight'=>$order->freight,

            'coupon_money'=>$order->coupon_money,

            'integral_balance'=>$order->integral_balance,

            'member_name'=>$member->nick_name,

            'member_mobile'=>$member->mobile,

            'member_face'=>$member->face,

            'level_name'=>(isset($level_info) && $level_info)?$level_info['name']:null,

            'items'=>$items,

            'order_send_time'=>$order->order_send_time,

            'percentage'=>sprintf("%.2f",$percentage),

            'boss_real_receive'=>sprintf("%.2f",$boss_real_receive),

            'partner_role_name'=>$partner_role_name,

            //'level'=>LevelModel::where(['shop_id'=>$this->request->shopId,'is_delete'=>0,'level_id'=>$member->level_id])->value('name'),

            'is_mix_pay_type'=>$order->mix_pay_type?1:0,

            'platform_money'=>$order->platform_money,

            'money'=>$order->money,

            'weixin'=>$order->weixin,

            'refund_money'=>$order->refund_money,

            'refund_order'=>$refund_order,

            'mix_pay_money'=>$mix_pay_money,

            'order_record_list'=>$record_return['list'],

            'write_off_list'=>isset($write_off)?$write_off['list']:[],

            'valid_time_list'=>isset($valid_time)?$valid_time:[],

            'residue_list'=>isset($residue)?$residue['list']:[],

            'youhui_price'=>$youhui_price

        ];



        return $this->success(['detail'=>$detail]);

    }

    function valid_write_off($datas,$item){
        $where = [
            ['is_delete','=',0],
            ['order_id','=',$datas->order_id],
            ['order_item_id','=',$item->order_item_id],
        ];
        $group_detail = OrderGoodsGroupDetailModel::where($where)->select()->toArray();
        $num = $remain_num = 0;
        $write_off = [];
        foreach ($group_detail as $k=>$v){
            if($v['use_condition']!=1) $is_many_write_off = 1;
            $num += $v['num'];
            $remain_num += $v['remain_num'];
            if($v['use_condition']!=1 && $v['num']>2 && $v['remain_num']>0){
                //核销数据
                $hx = GoodsWriteOffModel::where(['order_goods_group_detail_id'=>$v['order_goods_group_detail_id'],'goods_id'=>$v['goods_id']])->order(['add_time'=>'asc'])->select()->toArray();
                $v['is_effect'] = 1;
                //套餐详情有效期
                if($v['end_type']==1 && $hx){
                    $first_time = strtotime($hx[0]['add_time']);
                    if($v['end_time_type'] == 1){
                        $v['start_time'] = date('Y-m-d H:i:s',$datas->pay_time);
                        $v['end_time'] = date("Y-m-d",$first_time + $v['end_time_num'] * 86400)." 23:59:59";
                    }else{
                        $v['start_time'] = date('Y-m-d H:i:s',$datas->pay_time);
                        $v['end_time'] = GetMonth($first_time,$v['end_time_num']);

                    }
                    if(time()<strtotime($v['start_time']) && time()>strtotime($v['end_time'])){
                        $v['is_effect'] = 0;
                    }
                }
                //$v['write_off'] = $hx;
                $write_off[] = $v;
            }
        }
        return $write_off;
    }
    /*结算订单详情*/
    public function settlementOrderDetail(){
        $type = $this->request->param('type');//1买单2普通
        $order_id = $this->request->param('order_id');
        if($order_id==0) return $this->error('订单不存在#');

        if($type==1){
            $order_model = new BuyOrderModel();
            if(null === $order = $order_model::with(['refundLogs'=>function($query){
                    $query->where(['is_delete'=>0]);
                }])->where(['buy_order_id'=>$order_id])->find()) return $this->error('订单不存在#');
        }else{
            $order_model = new GoodsOrderModel();
            $order_model = $order_model::with(['skus','refundLogs'=>function($query){
                $query->where(['is_delete'=>0]);
            }]);
            if(null === $order = $order_model->where(['order_id'=>$order_id])->json(['order_send_time'],true)->find()) return $this->error('订单不存在#');
        }

        $order = $order->append(['add_time_format','pay_time_format','pay_type_mean']);

        if($order['shop_id'] != $this->request->shopId) return $this->error('订单不存在#');
        if($order['is_delete'] != 0) return $this->error('订单不存在#');

        //订单类型
        if($type==1){
            $order_type = '买单';
        }else{
            if($order['logistics_type']==1){
                $order_type = '快递';
            }else if($order['logistics_type']==2){
                $order_type = '自提';
            }else if($order['logistics_type']==3){
                $order_type = '同城';
            }else{
                $order_type = '到店';
            }

        }
        $order['order_type'] = $order_type;

        $shop_id = $this->request->shopId;
        $member = MemberModel::with(['memberlevel'=>function($query)use($shop_id,$order){
            $query->where(['shop_id'=>$shop_id,'is_delete'=>0]);
        }])->where(['member_id'=>$order->member_id])
            ->field('member_id,nick_name,face,mobile')
            ->find();
        if(empty($member))  return $this->error('会员不存在');
        $youhui_price= 0;
        //消费信息
        if($type==2){
            $goods_item = $order['skus'];
            foreach ($goods_item as $k=>$v){
                //单位
                $goods = GoodsModel::with(['unit'])->where(['goods_id'=>$v['goods_id']])->find();
                if($goods && isset($goods['unit']) && $goods['unit']){
                    $unit = $goods['unit']['group_detail_name'];
                }
                $goods_item[$k]['unit'] = isset($unit)?$unit:'无';
                $goods_item[$k]['num'] = $k + 1;
                if($v['type']==2){
                    $goods_item[$k]['type_name'] = '产品';
                }else{
                    $goods_item[$k]['type_name'] = '套餐';
                }
                $toal_chargeback_num = ChargebackModel::where(['shop_id'=>$this->request->shopId,'order_item_id'=>$v['order_item_id'],'is_delete'=>0])->sum('num');
                $turnover = $v['goods_num'] - $toal_chargeback_num;
                $reduce_money = sprintf("%.2f",($v['goods_original_price'] - $v['goods_price']) * $turnover);
                $goods_item[$k]['vip_discount_type'] = $v['vip_discount_type']>0?$v['vip_discount_type']:0;
                $goods_item[$k]['discount_detail'] = $v['vip_discount_type']>0?$v['discount_detail']:0;
                $goods_item[$k]['reduce_money'] = $v['vip_discount_type']>0?$reduce_money:0;
                $youhui_price +=$reduce_money;
            }
            $order['skus'] = $goods_item;
        }
        //会员等级
        if($member['memberlevel']['level_id']){
            $level_model = new LevelModel();
            $level = $level_model->getById(['level_id'=>$member['memberlevel']['level_id'],'is_delete'=>0]);
            $member['level_name'] = isset($level['name'])?$level['name']:'';
        }else{
            $member['level_name'] = '普通会员';
        }
        unset($member['memberlevel']);
        //结算信息
        if($type==1){
            $js_where[] = ['b_order_id','=',$order_id];
            $order['total_price'] = $order['balance'];
        }else{
            $js_where[] = ['order_id','=',$order_id];
            $order['pay_money'] = $order['need_pay'];
        }
        //优惠金额
        $m_coupon = MemberCouponModel::where(['member_coupon_id'=>$order['member_coupon_id']])->find();
        $order['order_youhui_money'] = $m_coupon?$m_coupon['name'].'-￥'.$order['coupon_money']:'￥0.00';

        //实收

        if($type==1){
            $order['boss_real_receive'] = sprintf("%.2f",$order['pay_money'] - $order['refund_money']);
            if($order['vip_balance']>0){
                $order['vip_discount_type'] = 1;
                $order['discount_detail'] = ($order['pay_money']*10)/($order['pay_money']+$order['vip_balance']);
                $order['reduce_money'] = $order['vip_balance'];
                $youhui_price += $order['reduce_money'];
            }
        }else{
            $order['boss_real_receive'] = sprintf("%.2f",$order['need_pay'] - $order['refund_money']);
        }

        $settlement_info = SettleOrderModel::where(['shop_id'=>$this->request->shopId])->where($js_where)->field('settle_money,buckle_money,service_money,lock_money,partner_bonus,promotion_money,consume_money')->find();
        if($settlement_info) $settlement_info['settle_money'] = sprintf("%.2f",$settlement_info['settle_money']);
        if($settlement_info) $settlement_info['consume_money'] = sprintf("%.2f",$settlement_info['consume_money']);
        if($settlement_info) $settlement_info['buckle_money'] = sprintf("%.2f",$settlement_info['buckle_money']);
        if($settlement_info) $settlement_info['service_money'] = sprintf("%.2f",$settlement_info['service_money']);
        if($settlement_info) $settlement_info['lock_money'] = sprintf("%.2f",$settlement_info['lock_money']);
        if($settlement_info) $settlement_info['partner_bonus'] = sprintf("%.2f",$settlement_info['partner_bonus']);
        if($settlement_info) $settlement_info['promotion_money'] = sprintf("%.2f",$settlement_info['promotion_money']);

        //操作日志
        if($type==1){
            $r_where['buy_order_id'] = $order_id;
        }else{
            $r_where['order_id'] = $order_id;
        }
        $r_where['shop_id'] = $this->request->shopId;
        //操作日志
        $record_return = OrderRecordModel::list($r_where,['r.add_time'=>'asc'],0,0,'r.order_id,r.buy_order_id,r.add_time,r.status,r.operate_id,a.username as operate_name,a.mobile');

        $return['order_record_list'] = $record_return['list'];
        $return['settlement_info'] = $settlement_info??(object)[];
        $return['order'] = $order;
        $return['member'] = $member;
        $return['youhui_price'] = $youhui_price;
        return $this->success($return);

    }
    /*买单订单添加/修改备注*/
    public function addBuyOrderRemarks(){
        $remarks = $this->request->param('remarks');
        $buy_order_id = $this->request->param('buy_order_id/d',0);
        if(null === $order = BuyOrderModel::where(['buy_order_id'=>$buy_order_id,'shop_id'=>$this->request->shopId])->find()){
            return $this->error('买单订单不存在');
        }
        $order->remarks = $remarks;
        $order->save();

        return $this->success('操作成功');

    }
    /**
     * 商品订单退款（可部分）
     */
    public function orderRefund(){
        $order_id = $this->request->param('order_id/d',0);
        $refund_type = $this->request->param('refund_type/d',1);//1全额退款2部分金额退款
        $refund_money = $this->request->param('refund_money',0);
        $reason = $this->request->param('reason');

        if(null === $order = GoodsOrderModel::where(['order_id'=>$order_id,'is_paid'=>1,'shop_id'=>$this->request->shopId])->find()){
            return $this->error('订单不存在');
        }
        //判断订单是否已申请退款
        if($order['status'] == 11) return $this->error('订单已在退款列表');
        if($order['status'] == 12) return $this->error('订单已全部退款');
        if($order['status'] == 1) return $this->error('该订单未支付');
        if($order['is_settle'] ==1) return $this->error('该订单已结算不能退款');
        if($refund_type==2 && $refund_money <= 0) return $this->error('退款金额必须大于0');
        if($refund_money > ($order['need_pay'] - $order['refund_money'])) return $this->error('退款金额大于可退款金额');
        if($refund_type == 2 && $order['need_pay'] == $refund_money) return $this->error('部分退款金额已是全额金额，请选全额退款');
        if($order['need_pay'] == $order['refund_money']) return $this->error('已全部退完');
        if($refund_type == 1 && $order['refund_money']>0) return $this->error('已部分退款');

        $refund_money = $refund_type==1?$order['need_pay']:$refund_money;

        Db::startTrans();
        try{

            //退还优惠券
            if(!empty($order['member_coupon_id'])){

                if(null === $myCoupon = MemberCouponModel::find($order['member_coupon_id'])){

                    return $this->error('优惠券不存在');

                }

                if($myCoupon->status == 0){

                    return $this->error('优惠券还未使用');

                }

                $myCoupon->status = 0;

                $myCoupon->save();

                LogsLogic::coupon($this->request->shopId, $order['member_id'], 1, 23, $order['member_coupon_id'], '', 0);

            }

            //退还积分
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $order['member_id']);

            if(!empty($order['use_integral'])){ //使用积分

                $res = $MemberWalletLogic->addIntegal($order['use_integral'], 23);

                if($res == false){

                    return $this->error($MemberWalletLogic->getError());

                }

            }
            if(!empty($order['mix_pay_type'])){
                $refund_money = $refund_type==1?$order->need_pay:$refund_money;
                $return = order_mix_refund_money($order,$refund_money);
                if(!$return['code']){
                    return  $this->error($return['error']);
                }
                $refund_money = $return['refund_platform_money'] + $return['refund_money'] + $return['refund_weixin'];
                $refund_platform_money = $return['refund_platform_money'];
                $refund_price = $return['refund_money'];
                $refund_weixin = $return['refund_weixin'];
            }else{
                $refund_platform_money = $refund_price = $refund_weixin = 0;
                if($order['pay_type'] == 'weixin'){
                    $pay_info = $order['pay_info'];
                    $pay_info['refund_total_fee'] = $refund_money * 100;
                    $pay_info['out_refund_no'] = $refund_order_sn = createOrderSn($order_id,5);
                    //支付原路退还
                    $PaymentGoodsOrderHelper = new PaymentGoodsOrderHelper($this->request->shopId);
                    $re= $PaymentGoodsOrderHelper->refundInTheSameWayBf($pay_info);

                    if($re['result_code']=='FAIL'){
                        return $this->error($re['err_code_des']);
                    }
                    $refund_weixin = $refund_money;
                }

                if($order['pay_type'] == 'money'){
                    $res = $MemberWalletLogic->rebackBalance($refund_money, 0 , 23); //商城购物使用
                    if($res == false){
                        return $this->error($MemberWalletLogic->getError());
                    }
                    $refund_price = $refund_money;
                }

                if($order['pay_type'] == 'platform_money'){
                    $member = MemberModel::where(['member_id'=>$order['member_id']])->find();

                    $money = $member->money;

                    $member->money = $member->money+$refund_money;
                    $member->save();

                    LogsLogic::money($this->request->shopId, $order['member_id'], 23, 1, $money,$refund_money, $member->money+$refund_money,0,$order['order_id'],0);
                    $refund_platform_money = $refund_money;
                }
            }


            $order_refund = new OrderRefundModel();

            if(isset($refund_order_sn)) $order_refund->refund_order_sn = $refund_order_sn;

//            $order_refund->shop_id = $this->request->shopId;
//            $order_refund->order_id = $order_id;
//            $order_refund->member_id = $order['member_id'];
//            $order_refund->refund_price = $refund_money;
//            $order_refund->remain_money = $order['need_pay'] -$order['refund_money'] - $refund_money;
//            $order_refund->pay_money = $order['need_pay'];
//            $order_refund->status = 1;
//            $order_refund->reason = $reason;
//            $order_refund->refund_type = $refund_type;
//            $order_refund->update_time = date('Y-m-d H:i:s');
//            $order_refund->operate_id = $this->request->accountId;
//            $order_refund->refund_platform_money = $refund_platform_money;
//            $order_refund->refund_money = $refund_price;
//            $order_refund->refund_weixin = $refund_weixin;
//            $order_refund->save();

            $order_refund_data['shop_id'] = $this->request->shopId;
            $order_refund_data['order_id'] = $order_id;
            $order_refund_data['member_id'] = $order['member_id'];
            $order_refund_data['refund_price'] = $refund_money;
            $order_refund_data['remain_money'] = $order['need_pay'] -$order['refund_money'] - $refund_money;
            $order_refund_data['pay_money'] = $order['need_pay'];
            $order_refund_data['status'] = 1;
            $order_refund_data['reason'] = $reason;
            $order_refund_data['refund_type'] = $refund_type;
            $order_refund_data['update_time'] = date('Y-m-d H:i:s');
            $order_refund_data['operate_id'] = $this->request->accountId;
            $order_refund_data['refund_platform_money'] = $refund_platform_money;
            $order_refund_data['refund_money'] = $refund_price;
            $order_refund_data['refund_weixin'] = $refund_weixin;
            $order_refund_id = OrderRefundModel::insertGetId($order_refund_data);

            //修改订单状态
            if(($order['refund_money'] + $refund_money) == $order->need_pay)   $order->status = 12;
            $order->reason = $reason;
            $order->edit_time = date('Y-m-d H:i:s');
            $order->refund_money = $order['refund_money'] + $refund_money;
            $order->save();

            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = $refund_type;
            $r_data['order_refund_id'] = $order_refund_id;
            $r_data['operate_id'] = $this->request->accountId;
            add_record(0,$order_id,$r_data);
            //是否全部退完
            if($order->refund_money == $order['need_pay']){
                //删除分佣数据
                ShopBalanceLogsModel::where(['order_id'=>$order_id])->delete();
                //删除股东推广分成
                MemberMoneyDetailModel::where(['g_order_id'=>$order_id,'type'=>4])->delete();
                //删除股东佣金表
                PartnerCommissionModel::where(['order_id'=>$order_id,'type'=>'普通订单'])->delete();
            }

            Db::commit();

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
        return $this->success('操作成功');

    }
    /**
     * 售后退单(只修改数量-可以小数，不退款)
     */
    public function chargeback(){
        $order_id = $this->request->param('order_id/d',0);
        $order_item_id = $this->request->param('order_item_id/d',0);
        $num = $this->request->param('num/f');
        $reason = $this->request->param('reason');

        if(null === $order = GoodsOrderModel::where(['order_id'=>$order_id,'is_paid'=>1,'shop_id'=>$this->request->shopId])->find()){
            return $this->error('订单不存在');
        }
        if(null === $order_item = GoodsOrderItemModel::where(['order_id'=>$order_id,'order_item_id'=>$order_item_id])->find()){
            return $this->error('订单不存在');
        }
        if($num > $order_item['goods_num']) return $this->error('退单数量超过购买数量');
        $remain_num = $order_item['goods_num'] - $num;
        //是否有退单记录
        $chargeback = ChargebackModel::where(['order_id'=>$order_id,'order_item_id'=>$order_item_id])->order(['add_time'=>'desc'])->find();
        if($chargeback){
            if($num > $chargeback['remain_num']) return $this->error('退单数量超过剩余数量');
            $remain_num = $chargeback['remain_num'] - $num;
        }
        Db::startTrans();
        try{
            $data['shop_id'] = $this->request->shopId;
            $data['member_id'] = $order['member_id'];
            $data['order_id'] = $order_id;
            $data['order_item_id'] = $order_item_id;
            $data['num'] = $num;
            $data['remain_num'] = $remain_num;
            $data['reason'] = $reason;
            $data['add_ip'] = request()->ip();
            ChargebackModel::insertGetId($data);
    
            GoodsOrderModel::update(['edit_time'=>date('Y-m-d H:i:s'),'is_chargeback'=>1],['order_id'=>$order_id,'shop_id'=>$this->request->shopId]);
    
            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = 9;
            $r_data['order_refund_id'] = 0;
            $r_data['operate_id'] = $this->request->accountId;
            $r_data['num'] = $num;
            $r_data['order_item_id'] = $order_item_id;
            add_record(0,$order_id,$r_data);
            
            Db::commit();

            return $this->success('操作成功');
            
        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }

}

